<template>
  <div class="the-list">

    <div class="panel-search">
      <el-form inline :model="tableData.query" class="demo-form-inline">
        <el-form-item label="用户信息">
          <el-input v-model="tableData.query.keywords" style="width:240px" placeholder="通过用户ID、手机号、昵称搜索" clearable/>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="tableData.query.sex" placeholder="性别">
            <el-option label="全部" value="" />
            <el-option v-for="(item,index) in userList.sex" :key="index" :label="item.name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号类型">
          <el-select v-model="tableData.query.identification" placeholder="账号类型">
            <el-option label="全部" value="" />
            <el-option v-for="(item,index) in userList.identification" :key="index" :label="item.name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态">
          <el-select v-model="tableData.query.status" placeholder="账号状态" style="width: 240px">
            <el-option label="全部" value="" />
            <el-option v-for="(item,index) in userList.status" :key="index" :label="item.name" :value="item.key" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="所在省市">
          <el-cascader :model-value="tableData.special.area" @update:modelValue="tableFn.areasChange" :props="tableFn.areaLazyData" />
        </el-form-item> -->
        <el-form-item label="注册时间">
          <el-date-picker :model-value="tableData.special.createdAt" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"  @update:modelValue="tableFn.detetimeChange($event,'create')"/>
        </el-form-item>
        <el-form-item label="最近登录">
          <el-date-picker :model-value="tableData.special.lastLogin" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"  @update:modelValue="tableFn.detetimeChange($event,'login')" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tableFn.onSubmit">搜索</el-button>
          <el-button type="primary" @click="tableFn.onResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="panel-table">
      <div class="table-head">
        <span>数据列表</span>
        <div>
          <el-button v-loading="exportData.isLoading" type="primary" @click="exportFn.exportTableData">导出数据</el-button>
        </div>
      </div>
      <el-table :data="tableData.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>
        <el-table-column prop="customerId" label=" 品客ID" width="80px"/>
        <el-table-column prop="phone" label="手机号码" />
        <el-table-column prop="nickname" label="用户昵称" >
          <template #default="{row}">
            <p v-if="row.nickname">{{row.nickname}}</p>
            <p v-else class="isEmpty">--</p>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80px">
          <template #default="{row}">
            {{getItemFromArray(userList.sex,row.sex) || "--"}}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="identification" label="类型" width="80px">
          <template #default="{row}">
            {{getItemFromArray(userList.identification,row.identification) || "--"}}
          </template>
        </el-table-column> -->
        <el-table-column prop="vipTypeDesc" label="类型" width="80px"/>
        <el-table-column prop="registerFrom" label="注册来源" width="100px">
          <template #default="{row}">
            {{row.registerFrom||'--'}}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="provinceName" label="所在省" width="80px">
          <template #default="{row}">
            <p v-if="row.provinceName">{{row.provinceName}}</p>
            <p v-else class="isEmpty">--</p>
          </template>
        </el-table-column>
        <el-table-column prop="cityName" label="所在市" width="80px">
          <template #default="{row}">
            <p v-if="row.cityName">{{row.cityName}}</p>
            <p v-else class="isEmpty">--</p>
          </template>
        </el-table-column> -->
        <el-table-column prop="createdAt" label="注册时间" />
        <el-table-column prop="lastLogin" label="最近登录时间" />
        <el-table-column prop="status" label="账号状态" width="88px">
          <template #default="{row}">
            <span :style="{color:['#D9001B','#70B603','#c5c5c5'][row.status]}">{{getItemFromArray(userList.status,row.status) || "--"}}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="76px">
          <template #default="{row}">
            <el-button size="small" type="primary" plain @click="tableFn.goToDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
      <pagination :total="tableData.total" v-model:page="tableData.query.page" v-model:limit="tableData.query.pageSize" @pagination="tableFn.getTableData" />
      </div>

    </div>

  </div>
</template>

<script>
export default {
  name: "VideouserList",
};
</script>
<script setup>
import { reactive } from "vue";
import { getCustomerList } from "@/api/videouser.js";
import { getProvince,getCity } from "@/api/user.js";
import { useRouter } from "vue-router";
import Pagination from "@/components/Pagination";
import { userList,getItemFromArray,exportListData }  from "@/utils/tool.js";
import { ElMessage } from 'element-plus';


const { $data:tableData, $fn:tableFn } = (()=>{
  let router = useRouter();
  const backup = {
    query: {
      keywords:"",//是	[string]		
      sex:"",//性别:0表示中性，1男，2女 (全部就不传)	是	[string]		
      identification:"",//身份标识:普通0、平台1、达人2 (全部就不传)	是	[string]		
      status:"",//状态 0：封禁；1、正常 (全部就不传)	是	[string]		
      provinceId:"",//省 (全部就不传)	是	[string]		
      cityId:"",//市 (全部就不传)	是	[string]		
      createdAtStart:"",
      createdAtEnd:"",
      lastLoginStart:"",
      lastLoginEnd:"",
      pageSize: 10,
      page: 1,
    },
  };

  const $data = reactive({
    query: { ...backup.query },
    special:{
      area:[],
      createdAt:[],
      lastLogin:[],
    },
    list: [],
    provinceList:[],//省份列表
    total: 0,
  });
  
  const $fn = {
    getTableData() {
      getCustomerList($data.query).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    onResetQuery() {
      $data.query = { ...backup.query };
      $data.special.area = [];
      $data.special.createdAt = [];
      $data.special.lastLogin = [];
      $fn.getTableData();
    },
    onSubmit() {
      $fn.getTableData();
    },
    areaLazyData:{
      lazy: true,
      lazyLoad(node, resolve) {
        // console.log("lazy load:", node);
        const { level,value } = node;
        if(level===0){
          getProvince().then(({code,data=[]})=>{
            if(code===0){
              const nodes = data.map((item) => ({
                value: item.id,
                label: item.provinceName,
                leaf: false,
              }));
              resolve([{
                value: "",
                label: "全部",
                leaf: true,
              },...nodes]);
            }
          })
        }else{
          getCity({provinceId:value}).then(({code,data})=>{
            if(code===0){
              const nodes = data.map((item) => ({
                value: item.id,
                label: item.cityName,
                leaf: true,
              }));
              resolve([{
                value: "",
                label: "全部",
                leaf: true,
              },...nodes]);
            }
          })
        }
      },
    },
    areasChange(areas=[]){
      $data.special.areas = areas;
      $data.query.provinceId = areas[0]||"";
      $data.query.cityId = areas[1]||"";
    },
    detetimeChange(time,type){
      time = time||[];
      if(type==="create"){
        $data.special.createdAt = time;
        $data.query.createdAtStart = time[0]||"";
        $data.query.createdAtEnd = time[1]||"";
      }else if(type==="login"){
        $data.special.lastLogin = time;
        $data.query.lastLoginStart = time[0]||"";
        $data.query.lastLoginEnd = time[1]||"";
      }
    },
    goToDetail(row,view) {
      let addView = view?"?view="+view:"";
      router.push(`/videouser/detail/${row.customerId}${addView}`);
    }
  };

  $fn.getTableData();

  return {
    $data,
    $fn,
  };
})();

const { $data:exportData, $fn:exportFn } = (()=>{
  const backup={
    tableName: "用户表",
    options: [
      //导出的项
      { key: "customerId", name: " 品客ID" },
      { key: "phone", name: "手机号码" },
      { key: "nickname", name: "用户昵称" },
      { key: "sex", name: "性别" },
          // {{getItemFromArray(userList.sex,row.sex) || "--"}}
      { key: "identification", name: "类型" },
          // {{getItemFromArray(userList.identification,row.identification) || "--"}}
          // {{row.picoOpusKindOfNum.worksNum}} / {{row.picoOpusKindOfNum.shareNum}} / {{row.picoOpusKindOfNum.commentNum}} / {{row.picoOpusKindOfNum.likeNum}}
      { key: "createdAt", name: "注册时间" },
      { key: "lastLogin", name: "最近登录时间" },
      { key: "status", name: "账号状态" },
          // <span :style="{color:['#D9001B','#70B603'][row.status]}">{{getItemFromArray(userList.status,row.status) || "--"}}</span>
    ]
  }
  const $data = reactive({
    isLoading: false,
  })
  
  const $fn={
    exportTableData() {
      $data.isLoading = true;
      getCustomerList({ ...tableData.query, pageSize: tableData.total }).then(
        ({ code, data }) => {
          if (code === 0) {
            if(!data?.items?.length){
              $data.isLoading = false;
              ElMessage.warning("数据为空！");
              return;
            }
            let resList = $fn.dealExportData(data.items);
            exportListData(backup.tableName, backup.options, resList);
            $data.isLoading = false;
          }
        }
      );
    },
    dealExportData(list){
      let mlist = list||[];
      // 处理特殊项
      for(let prop of mlist){
        prop.sex = getItemFromArray(userList.sex,prop.sex);
        prop.identification = getItemFromArray(userList.identification,prop.identification);
        prop.likeEtc = `${prop.picoOpusKindOfNum?.worksNum||0} / ${prop.picoOpusKindOfNum?.shareNum||0} / ${prop.picoOpusKindOfNum?.commentNum||0} / ${prop.picoOpusKindOfNum?.likeNum||0}`;
        prop.walletBalance = `${prop.walletBalance}（折合：¥ ${prop.walletBalance / 100}）`;
        prop.welfareAmount = prop.welfareAmount / 100;
        prop.status = getItemFromArray(userList.status,prop.status);
      }
      return mlist;
    }
  }
  
  return {
    $data,
    $fn,
  };
})();

</script>

<style scoped lang="scss">
@import "@/styles/tablePage.scss";
.the-list {
  height: 100%;
}
.el-form-item {
  margin-bottom: 8px;
}
</style>